package com.hopu.interceptor;

import com.alibaba.fastjson.JSON;
import com.feng.common.util.Result;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Writer;

/**
* @Description: SpringMVC的拦截器
* @Author: xing
* @Date: 2022/11/18
*/


//springMVC的拦截器     去继承HandlerInterceptorAdapter抽象类
public class LoginIntercepter extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
//获取当前的session
        HttpSession session = request.getSession();

        //获取请求路径
        String uri = request.getRequestURI();


        //给需要的被拦截uri做判断,把需要拦截字符串包含在uri内即可
        //暂时先做一个 拦截器 ,除了登陆以外全部都需要可以被拦截
        //uri.contains("user/login")
//        uri.contains(".html")||uri.contains("user/login") || (session.getAttribute("username") != null)
        if (uri.contains(".html")||uri.contains("user/login") || (session.getAttribute("username") != null)) {


            //允许通过拦截器不做任何其他动作
            return true;
        } else {

            //实例化Result,为了返回错误码
            Result result = new Result();
            result.setCode("40003");
            result.setMsg("no security");
            //直接响应前台的请求
            Writer writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
            return false;
        }
   }
}
